"""
KimiController模块
封装了所有与Kimi页面交互的复杂逻辑。
"""
import asyncio
from typing import Callable, List, Dict, Any, Optional

from playwright.async_api import Page as AsyncPage, expect as expect_async

from config import (
    KIMI_INPUT_SELECTOR, KIMI_SEND_BUTTON_SELECTOR, 
    KIMI_RESPONSE_SELECTOR, KIMI_NEW_CHAT_SELECTOR
)
from models import ClientDisconnectedError
from .kimi_operations import (
    initialize_kimi_page, submit_kimi_prompt, 
    wait_for_kimi_response, get_kimi_response_content,
    clear_kimi_chat_history
)

class KimiController:
    """封装了与Kimi页面交互的所有操作。"""

    def __init__(self, page: AsyncPage, logger, req_id: str):
        self.page = page
        self.logger = logger
        self.req_id = req_id

    async def _check_disconnect(self, check_client_disconnected: Callable, stage: str):
        """检查客户端是否断开连接。"""
        if check_client_disconnected(stage):
            raise ClientDisconnectedError(f"[{self.req_id}] Client disconnected at stage: {stage}")

    async def initialize_page(self) -> bool:
        """初始化Kimi页面"""
        return await initialize_kimi_page(self.page, self.req_id)

    async def submit_prompt(self, prompt: str, check_client_disconnected: Callable):
        """提交提示到Kimi页面。"""
        self.logger.info(f"[{self.req_id}] 向Kimi提交提示...")
        
        try:
            # 提交提示
            success = await submit_kimi_prompt(self.page, prompt, self.req_id)
            if not success:
                raise Exception("提交提示失败")
                
            await self._check_disconnect(check_client_disconnected, "提交提示后")
            
            # 等待响应开始
            await asyncio.sleep(1.0)
            
        except Exception as e:
            self.logger.error(f"[{self.req_id}] 提交提示过程中发生错误: {e}")
            raise

    async def get_response(self, check_client_disconnected: Callable) -> str:
        """获取Kimi响应内容。"""
        self.logger.info(f"[{self.req_id}] 等待并获取Kimi响应...")

        try:
            # 等待响应完成
            success = await wait_for_kimi_response(self.page, self.req_id)
            if not success:
                raise Exception("等待响应完成失败")
                
            await self._check_disconnect(check_client_disconnected, "等待响应完成后")

            # 获取最终响应内容
            final_content = await get_kimi_response_content(self.page, self.req_id)
            
            if not final_content or not final_content.strip():
                self.logger.warning(f"[{self.req_id}] 获取到的Kimi响应内容为空")
                return ""

            self.logger.info(f"[{self.req_id}] 成功获取Kimi响应内容 ({len(final_content)} chars)")
            return final_content

        except Exception as e:
            self.logger.error(f"[{self.req_id}] 获取Kimi响应时出错: {e}")
            raise

    async def clear_chat_history(self, check_client_disconnected: Callable):
        """清空Kimi聊天记录。"""
        self.logger.info(f"[{self.req_id}] 开始清空Kimi聊天记录...")
        await self._check_disconnect(check_client_disconnected, "开始清空聊天记录")

        try:
            success = await clear_kimi_chat_history(self.page, self.req_id)
            if not success:
                raise Exception("清空聊天记录失败")
                
            await self._check_disconnect(check_client_disconnected, "清空聊天记录后")
            self.logger.info(f"[{self.req_id}] Kimi聊天记录已清空")
            
        except Exception as e:
            self.logger.error(f"[{self.req_id}] 清空Kimi聊天记录过程中发生错误: {e}")
            raise